// App.js
import axios from 'axios'
import React, { useState, useEffect } from 'react'

const Filter = ({filter, handleFilterChange}) => {
  return (
    <form>
      <div>
        filter shown with<input value={filter} onChange={handleFilterChange}></input>
      </div>
    </form>
  )
}

const PersonForm = ({ persons, setPersons }) => {

  const [newName, setNewName] = useState('')
  const [newNumber, setNewNumber] = useState('')

  const handleNameChange = (event) => setNewName(event.target.value)
  const handleNumberChange = (event) => setNewNumber(event.target.value)

  const numberofPersons = persons.length
  const containsPerson = (persons, newName) =>
    persons.some((person) => person.name === newName)

  const addPerson = (event) => {
    event.preventDefault()
    const contains = containsPerson(persons, newName)
    console.log(contains)
    if (contains) {
      alert(`${newName} already in phonebook`)
      return
    }
    const personObject = {
      id: numberofPersons + 1,
      name: newName,
      number: newNumber,
    }
    setPersons(persons.concat(personObject))
    setNewName('')
    setNewNumber('')
  }

  return (
    <form onSubmit={addPerson}>
      <div>
        name: <input value={newName} onChange={handleNameChange} />
      </div>
      <div>number: <input value={newNumber} onChange={handleNumberChange} /></div>
      <div>
        <button type="submit">add</button>
      </div>
    </form>
  )
}

const Persons = ({persons}) => {
  return persons.map((person) => <p key={person.id}>{person.name} {person.number}</p>)
}

const App = () => {
  const [persons, setPersons] = useState([])
  const [filter, setFilter] = useState('')
  const [filterPersons, setFilterPersons] = useState(persons)
  
  const handleFilterChange = (event) => {
    setFilter(event.target.value)
    setFilterPersons(persons.filter((person) => (person.name.toLowerCase().indexOf(event.target.value.toLowerCase()) !== -1)))
  }

  useEffect(() => {
    console.log('effect')
    axios
      .get('http://localhost:3001/persons')
      .then(response => {
        console.log('promise fulfilled')
        setPersons(response.data)
      })
  }, [])
  console.log('render', persons.length, 'persons')

  return (
    <div>
      <h2>Phonebook</h2>
      <Filter filter={filter} handleFilterChange={handleFilterChange}></Filter>
      <h2>add a new</h2>
      <PersonForm persons={persons} setPersons={setPersons}></PersonForm>
      <h2>Numbers</h2>
      {filter===''?
      <Persons persons={persons}></Persons>:
      <Persons persons={filterPersons}></Persons>
      }
    </div>
  )
}

export default App

// index.js
import ReactDOM from 'react-dom'
import App from './App'

ReactDOM.render(
  <App/>,
  document.getElementById('root')
)